<template>
  <div>
    <a-card>
      <a-row :gutter="20">
        <a-col :span="6">
          <!--绑定属性值-->
          <a-input-search v-model="queryParam.username" allowClear placeholder="输入用户名查找" enter-button
                          @search="getUserList"/>
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="addUserVisiable = true">新增</a-button>
        </a-col>
      </a-row>

      <a-table rowKey="username" :columns="columns" :pagination='pagination' :dataSource="userlist" bordered>
        <span slot="role" slot-scope="role">{{ role == 1 ? '管理员' : '订阅者' }}</span>
        <!--数据也要回传-->
        <template slot="action" slot-scope="data">
          <div class="actionSlot">
            <a-button type="primary" icon="edit" style="margin-right: 20px" @click="editUser(data.ID)">编辑</a-button>
            <a-button type="danger" icon="delete" @click="deleteUser(data.ID)">删除</a-button>
          </div>
        </template>
      </a-table>
    </a-card>

    <!--新增用户区域-->
    <a-modal closable v-model="addUserVisiable" width="60%" title="新增用户" @ok="addUserOk" @cancel="addUserCancel" destroyOnClose>
      <a-form-model :model="userInfo" :rules="userRules" ref="addUserRef">
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="userInfo.username"></a-input>
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password">
          <a-input-password v-model="userInfo.password"></a-input-password>
        </a-form-model-item>
        <a-form-model-item label="确认密码" prop="checkpassword">
          <a-input-password v-model="userInfo.checkpassword"></a-input-password>
        </a-form-model-item>
        <a-form-model-item label="是否为管理员" prop="role" v-model="userInfo.role">
          <a-select defaultValue="1" style=":120px" @change="adminChange">
            <a-select-option key="1" value="1">是</a-select-option>
            <a-select-option key="2" value="2">否</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!--编辑用户区域-->
    <a-modal closable v-model="editUserVisiable" width="60%" title="编辑用户" @ok="editUserOk" @cancel="editUserCancel" destroyOnClose>
      <a-form-model :model="userInfo" :rules="userRules" ref="editUserRef">
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="userInfo.username"></a-input>
        </a-form-model-item>
        <a-form-model-item label="是否为管理员">
          <a-switch :default-checked="userInfo.role == 1?true:false" @change="adminChange" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: 'ID',
    dataIndex: 'ID',
    width: '5%',
    key: 'id',
    align: 'center'
  },
  {
    title: '用户名',
    dataIndex: 'username',
    width: '10%',
    key: 'username',
    align: 'center'
  },
  {
    title: '角色',
    dataIndex: 'role',
    width: '10%',
    key: 'role',
    scopedSlots: {customRender: 'role'},
    align: 'center'
  },
  {
    title: '操作',
    width: '20%',
    key: 'action',
    scopedSlots: {customRender: 'action'},
    align: 'center'
  },
]

export default {
  name: "UserList",
  data() {
    return {
      pagination: {
        pageSizeOptions: ['5', '10', '20'],
        pageSize: 5,
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共${total}条`,
      },
      userlist: [],
      columns,
      queryParam: {
        username: '',
        pagesize: 5,
        pagenum: 1,
      },
      userInfo: {
        id: 0,
        username: '',
        password: '',
        checkpassword: '',
        role: 2,
      },
      visiable: false,
      addUserVisiable: false,
      editUserVisiable: false,
      userRules: {
        username:[{required:true,message:'请输入用户名',trigger:'blur'},
          {min:4,max:12,message: '用户名应当在4到12个字符之间',trigger: 'blur'},],
        password: [{
          validator: (rule, value, callback) => {
            if (this.userInfo.password === "") {
              callback(new Error('请输入密码'))
            }
            if ([...this.userInfo.password].length>12||[...this.userInfo.password].length<2){
              callback(new Error('密码应当在2到12位之间'))
            }else {callback()}
          }, trigger: 'blur'
        }],
        checkpassword: [{
          validator: (rule, value, callback) => {
            if (this.userInfo.password !== this.userInfo.checkpassword) {
              callback(new Error('两次输入的密码不一致'))
            }else {callback()}
          }, trigger: 'blur'
        }]
      },
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const {data: res} = await this.$http.get('users', {
        params: {
          username: this.queryParam.username,
          pagesize: this.queryParam.pagesize,
          pagenum: this.queryParam.pagenum
        }
      })
      if (res.status != 200) return this.$message.error(res.message)
      this.userlist = res.data
      this.pagination.total = res.count
    },
    //跳转分页的逻辑
    handleTableChange(pagination, filters, sorter) {
      var pager = {...this.pagination}
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.queryParam.pagesize = pagination.pageSize
      this.queryParam.pagenum = pagination.current
      //如果分页的大小跟现有的大小有冲突，就回到第一页重新返回查找
      if (pagination.pageSize !== this.pagination.pageSize) {
        this.queryParam.pagenum = 1
        pager.current = 1
      }
      this.pagination = pager
      this.getUserList()
    },
    //删除的逻辑
    deleteUser(id) {
      this.$confirm({
        title: '提示：请确认操作？',
        content: '一旦删除，无法恢复',
        onOk: async () => {
          const {data: res} = await this.$http.delete(`user/${id}`)
          if (res.status != 200) return this.$message.error(res.message)
          this.$message.success('删除成功')
          this.getUserList()
        },
        //必须要加箭头函数，否则拿不到this
        onCancel: () => {
          this.$message.info('已取消删除')
        },
      })
    },
    //新增用户
    addUserOk() {
      this.$refs.addUserRef.validate(async (valid)=>{
        if (!valid) return this.$message.error('参数不符合要求，请重新输入')
        const {data:res} = await this.$http.post('user/add',{
          username:this.userInfo.username,
          password:this.userInfo.password,
          role:this.userInfo.role,
        })
        if (res.status !== 200) return this.$message.error(res.message)
        this.addUserVisiable = false
        this.$message.success('添加用户成功')
        this.getUserList()
      })
    },
    addUserCancel() {
      this.$refs.addUserRef.resetFields()
      this.addUserVisiable = false
    },
    //改变滑块状态
    adminChange(checked) {
      if (checked){
        this.userInfo.role = 1
      }else {
        this.userInfo.role = 2
      }
      console.log(this.userInfo.role)
    },
    //编辑用户
    async editUser(id){
      this.editUserVisiable = true
      const {data:res} = await this.$http.get(`user/${id}`)
      this.userInfo = res.data
      this.userInfo.id = id
    },
    editUserOk(){
      this.$refs.editUserRef.validate(async (valid)=>{
        if (!valid) return this.$message.error('参数不符合要求，请重新输入')
        console.log(this.userInfo.role)
        const {data:res} = await this.$http.put(`user/${this.userInfo.id}`,{
          username: this.userInfo.username,
          role: this.userInfo.role,
        })
        if (res.status != 200) return this.$message.error(res.message)
        this.editUserVisiable = false
        this.$message.success('编辑成功')
        this.getUserList()
      })
    },
    editUserCancel(){
      this.$refs.editUserRef.resetFields()
      this.editUserVisiable = false
    }
  },
}
</script>

<style scoped>
.actionSlot {
  display: flex;
  justify-content: center;
}
</style>